<?php

namespace App\Controllers;


use Framework\Database;
use Framework\Validation;
use Framework\Session;
use Framework\Authorisation;
use Framework\Middleware\Authorise;

class ListingController
{
    protected $db;

    public function __construct()
    {
        $config = require basePath('config/db.php');
        $this->db = new Database($config);
    }

    public function index()
    {
        $listings = $this->db->query('SELECT * FROM listing ORDER BY created_at DESC')->fetchAll();

        loadView('listings/index', [
            'listings' => $listings
        ]);
    }

    public function create()
    {
        loadView('listings/create');
    }

    public function show($params)
    {
        $id = $params['id'] ?? '';
        $params = [
            'id' => $id
        ];

        $listing = $this->db->query('SELECT * FROM listing WHERE id=:id', $params)->fetch();

        //检查listing是否存在
        if (!$listing) {
            ErrorController::notFound('该岗位不存在! ');
            return;
        }

        loadView('listings/show', [
            'listing' => $listing
        ]);
    }

    /**
     * 在数据库中存储数据
     */
    public function store()
    {
        $allowedFields = ['title', 'description', 'salary', 'tags', 'company', 'address', 'city', 'province', 'phone', 'email', 'requirements', 'benefits'];
        //从$_POST中提取允许的字段
        $newListingData = array_intersect_key($_POST, array_flip($allowedFields));
        //设置用户id
        $newListingData['user_id'] = Session::get('user')['id'];
        //清洗数据
        $newListingData = array_map('sanitize', $newListingData);
        //定义必须的字段
        $requiredFields = ['title', 'description', 'email', 'city', 'province'];
        //检查必须的字段
        $errors = [];
        foreach ($requiredFields as $field) {
            if (
                empty($newListingData[$field]) || !Validation::string($newListingData[$field])
            ) {
                $errors[$field] = ucfirst($field) . ' 为必需项';
            }
        }

        //处理可能的错误
        if (!empty($errors)) {
            loadView('listings/create', [
                //如果异常，重新创建列表并显示
                'errors' => $errors,
                'listing' => $newListingData
            ]);
        } else {
            //初始化
            $fields = [];
            foreach ($newListingData as $field => $value) {
                //向 $fields 数组末尾添加一个元素
                $fields[] = $field;
            }
            $fields = implode(', ', $fields);
            $values = [];
            //遍历
            foreach ($newListingData as $field => $value) {
                if ($value === '') {
                    $newListingData[$field] = null;
                }
                $values[] = ':' . $field;
            }
            $values = implode(', ', $values);
            //构建SQL插入语句
            $query = "INSERT INTO listing({$fields}) VALUES ({$values})";
            //执行
            $this->db->query($query, $newListingData);

            Session::setFlashMessage('success_message', '已成功创建职位! ');
            //重定向
            redirect('/listings');
        }
    }
    /**
     * 删除一个列表项
     */
    public function destroy($params)
    {
        //获取id
        $id = $params['id'];

        $params = [
            'id' => $id
        ];

        //查询列表项是否存在
        $listing = $this->db->query('SELECT * FROM listing WHERE id=:id', $params)->fetch();

        if (!$listing) {
            ErrorController::notFound("职位不存在! ");
            return;
        }

        if (!Authorisation::isOwner($listing->user_id)) {
            inspect($_SESSION);
            Session::setFlashMessage('error_message', '你没有权限删除此职位! ');
            return redirect('/listings/' . $listing->id);
        }

        //执行删除操作
        $this->db->query('DELETE FROM listing WHERE id = :id', $params);
        //设置提示信息
        Session::setFlashMessage('error_message', '删除职位成功! ');
        //删除成功后重定向
        redirect('/listings');
    }
    /**
     * 显示列表项编辑表单
     */
    public function edit($params)
    {
        $id = $params['id'] ?? '';
        //准备用于数据查询的参数
        $params = [
            'id' => $id
        ];
        //查询
        $listing = $this->db->query('SELECT * FROM listing WHERE id=:id', $params)->fetch();

        //检查查询结果
        if (!$listing) {
            ErrorController::notFound("职位不存在! ");
            return;
        }


        //授权
        if (!Authorisation::isOwner($listing->user_id)) {
            Session::setFlashMessage('error_message', '你没有权限修改此职位! ');
            return redirect('/listings/' . $listing->id);
        }




        //如果列表存在
        loadView('listings/edit', [
            'listing' => $listing

        ]);
    }
    /**
     * 更新列表数据
     */
    public function update($params)
    {
        $id = $params['id'] ?? '';
        //准备用于数据查询的参数
        $params = [
            'id' => $id
        ];
        //查询
        $listing = $this->db->query('SELECT * FROM listing WHERE id=:id', $params)->fetch();

        //检查查询结果
        if (!$listing) {
            ErrorController::notFound("职位不存在! ");
            return;
        }

        //授权
        if (!Authorisation::isOwner($listing->user_id)) {
            Session::setFlashMessage('error_message', '你没有权限修改此职位! ');
            return redirect('/listings/' . $listing->id);
        }



        //定义可以从表单接收的字段列表
        $allowedFields = ['title', 'description', 'salary', 'tags', 'company', 'address', 'city', 'province', 'phone', 'email', 'requrements', 'benefits'];

        //过滤
        $updateValues = array_intersect_key($_POST, array_flip($allowedFields));
        //清洗
        $updateValues = array_map('sanitize', $updateValues);

        $requiredFields = ['title', 'description', 'salary', 'email', 'city', 'province'];

        $errors = [];

        foreach ($requiredFields as $field) {
            if (empty($updateValues[$field]) || !Validation::string($updateValues[$field])) {
                $errors[$field] = ucfirst($field) . ' 为必需项! ';
            }
        }
        //如果存在错误
        if (!empty($errors)) {
            //重新加载
            loadView('listings/edit', [
                'listing' => $listing,
                'errors' => $errors
            ]);
            exit;
        } else {
            //构建sql
            $updateFields = [];
            foreach (array_keys($updateValues) as $field) {
                $updateFields[] = "{$field}=:{$field}";
            }

            $updateFields = implode(', ', $updateFields);

            $updateQuery = "UPDATE listing SET $updateFields WHERE id=:id";

            //更新数据
            $updateValues['id'] = $id;
            $this->db->query($updateQuery, $updateValues);

            Session::setFlashMessage('success_message', '职位信息已更新! ');

            redirect('/listings/' . $id);
        }
    }
    /**
     * 根据关键词的地点搜索列表
     */
    public function search()
    {
        $keywords = isset($_GET['keywords']) ? trim($_GET['keywords']) : '';
        $location = isset($_GET['location']) ? trim($_GET['location']) : '';

        $query = "SELECT * FROM listing WHERE 
        (title LIKE :keywords OR description LIKE :keywords OR
        tags LIKE :keywords OR company LIKE :keywords) AND
        (city LIKE :location OR province LIKE :location)";

        //准备查询参数
        $params = [
            'keywords' => "%{$keywords}%",
            'location' => "%{$location}%"
        ];

        //执行查询
        $listings = $this->db->query($query, $params)->fetchAll();

        //加载列表视图
        loadView('/listings/index', [
            'listings' => $listings,
            'keywords' => $keywords,
            'location' => $location
        ]);
    }
}
